/*
 *  Others.cpp
 *  T3nsors
 *
 *  Created by Michael Barriault on 10-09-23.
 *  Copyright 2010 MikBarr Studios. All rights reserved.
 *
 */

#include <T3nsors/Others.h>
#include <T3nsors/Macros.h>
#include <cstdlib>
#include <sys/time.h>
#include <iostream>
#include <sstream>
#include <cmath>

string itos(long long i) {
	std::ostringstream str;
	str << i;
	return str.str();
}

string ftos(double i) {
	std::ostringstream str;
	str << i;
	return str.str();
}

int stoi(string str) {
	std::istringstream istr(str);
	int i;
	istr >> i;
	return i;
}

double stof(string str) {
	std::istringstream istr(str);
	double i;
	istr >> i;
	return i;
}

void Alloc_Error(string id) {
	std::cout << "Allocation error making " << id << std::endl;
}

void print(string str, bool fl) {
#ifdef DEBUG
	std::cout << str << std::flush;
	if ( not fl ) std::cout << std::endl;
#endif
}

string timer(struct timeval before, int mult) {
	std::ostringstream str;
	struct timezone tzp;
	struct timeval now,lapsed;
	gettimeofday(&now,&tzp);
	if ( before.tv_usec > now.tv_usec ) {
		now.tv_usec += 1000000;
		now.tv_sec--;
	}
	lapsed.tv_usec = now.tv_usec - before.tv_usec; 
	lapsed.tv_sec = now.tv_sec - before.tv_sec; 
	int left = int(mult*(lapsed.tv_sec+double(lapsed.tv_usec)/1E6));
	if ( left > 3600 )
		str << left/3600 << "h ";
	if ( left > 60 )
		str << (left%3600)/60 << "m ";
	str << left%60 << "s" << std::flush;
	return str.str();
}

string bytes(long long int b) {
	char pre[10] = "BKMGTPEZY";
	int i=0;
	string rd = "";
	int rem;
	do {
		rem = b%1024;
		rd = itos(rem) + pre[i] + " " + rd;
		b = (b - rem)/1024;
		i++;
	} while ( b > 0);
	return rd;
}

double smoother(double x, double x0) {
	if ( fabs(x) < fabs(x0) )
		return pow(pow(x,2)-pow(x0,2),4);
	return 0.;
}

double dsmoother(double x, double x0) {
	if ( fabs(x) < fabs(x0) )
		return 8*x*pow(pow(x,2)-pow(x0,2),3);
	return 0.;
}

int step(double x) {
	if ( x > 0 ) return 1;
	else return 0;
}

string mkdir(string id) {
	return (std::string)"mkdir " + id + " 2> /dev/null";
}